<template>
    <el-drawer width="20vw" class="flex-drawer" direction="rtl" :close-on-click-modal="false" v-model="info.visible" @close="handleClose"  >
        <template #header>
            <div style="font-size:var(--18FontSize); font-weight:500; color:#525866;">{{ `${ info.forEdit ? '更新' : '新增' }巡检项` }}</div>
        </template>
        <el-form class="flex-form" ref="myForm" :model="form" :rules="rules" label-position="top">
            <el-form-item label="巡检项名称" prop="itemName">
                <FlexInput :data="{ paramKey:'itemName' }" :form="form" />
            </el-form-item>
            <el-form-item label="标准与要求" prop="itemNormAndDemand">
                <FlexInput :data="{ paramKey:'itemNormAndDemand', type:'textarea', placeholder:'例：检查外观是否磨损' }" :form="form" />
            </el-form-item>
            <el-form-item label="检查方法及工具" prop="checkWayAndTool">
                <FlexInput :data="{ paramKey:'checkWayAndTool', type:'textarea', placeholder:'例：目测' }" :form="form" />
            </el-form-item>
            <el-form-item label="数值记录" prop="needValueRemark" class="flex-form-item" style="display:flex; align-items: center;">
                <FlexSwitch :data="{ paramKey:'needValueRemark' }" :form="form" />
            </el-form-item>
            <el-form-item v-if="form.needValueRemark" label="数值名称" >
                <FlexInput :data="{ paramKey:'valueName' }" :form="form" />
            </el-form-item>
            <el-form-item v-if="form.needValueRemark" label="数值单位" >
                <FlexInput :data="{ paramKey:'valueUnit' }" :form="form" />
            </el-form-item>
            <el-form-item label="巡检周期" prop="cycleId">
                <FlexSelect :payload="cycleList" :total="total" :data="flexSelectOption" @search="fetchCycleList"  :form="form" />
            </el-form-item>
        </el-form>
        <div style="display:flex; gap:var(--mPadding); margin-top:var(--lPadding); ">
            <div class="flex-btn middle opacity" style="flex:1;" @click="handleClose">取消</div>
            <div class="flex-btn middle" style="flex:1;" @click="handleSubmit">确认</div>
        </div>
    </el-drawer>
</template>

<script setup>
    import { watch, ref, reactive, nextTick, onMounted, onUnmounted } from 'vue';
    import { getCycleList  } from '@/api/cycle.js';
    import { addOrUpdateInspection } from '@/api/tpl.js';
    import { ElMessage } from 'element-plus';
    import FlexInput from '@/components/FlexInput.vue';
    import FlexSelect from '@/components/FlexSelect.vue';
    import FlexSwitch from '@/components/FlexSwitch.vue';
    const flexSelectOption = { paramKey:'cycleId', fullWidth:true, hasPagination:true, labelName:'cycleName', labelKey:'cycleId' };
    const props = defineProps({
        info:{ type:Object },
        tplCode:{ type:String },
        targetId:{ type:String },
        forObj:{ type:Boolean }
    });
    const emit = defineEmits(['update:info', 'refresh']);
    const cycleList = ref([]);
    const total = ref(0);
    const myForm = ref(null);
    const form2 = ref({ selectName:'', selectMode:[0, 1, 2] });
    const form = reactive({
        itemName:'',   
        itemNormAndDemand:'',
        checkWayAndTool:'',
        needValueRemark:false,
        valueName:'',
        valueUnit:'',
        cycleId:''
    });
    const rules = reactive({
        itemName:[{ required:true, message:'巡检项名称不能为空',  trigger:'blur' }],
        cycleId:[{ required:true, message:'请选择巡检周期',  trigger:'blur' }],
    });
    
    // 重置状态
    function handleClose(){
        Object.keys(form).forEach(key=>{
            form[key] = key === 'needValueRemark' ? false : ''
        })
        myForm.value.clearValidate();
        props.info.visible = false;
    }
    function handleSubmit(){
        myForm.value.validate(valid=>{
            if ( valid ){              
                let obj = { 
                    itemName:form.itemName, 
                    itemNormAndDemand:form.itemNormAndDemand, 
                    checkWayAndTool:form.checkWayAndTool,
                    needValueRemark:form.needValueRemark ? 1 : 0,
                    cycleId:form.cycleId,
                };
                if ( props.forObj ) {
                    obj.targetId = props.targetId;
                } else {
                    obj.templateCode = props.tplCode;
                }
                if ( form.needValueRemark ) {
                    obj.valueName = form.valueName;
                    obj.valueUnit = form.valueUnit;
                }
                if ( props.info.forEdit ) {
                    if ( props.forObj ) {
                        obj.itemTargetId = props.info.row.itemTargetId;
                    } else {
                        obj.itemId = props.info.row.itemId;
                    }
                }
                addOrUpdateInspection(obj, props.info.forEdit, props.forObj)
                .then(res=>{
                    if ( res.data.code === 200 ) {
                        ElMessage({
                            type:'success',
                            message:`${props.info.forEdit ? '更新' : '新增'}巡检${ props.forObj ? '对象' : '模板'}巡检项成功`
                        });
                        handleClose();
                        emit('refresh');
                    }
                })  
            }                                        
        })
    }
    watch(()=>props.info, ()=>{
        if ( props.info.forEdit ){
            Object.keys(form).forEach(key=>{
                form[key] = props.info.row[key];
            });
            form['needValueRemark'] = props.info.row['needValueRemark'] === 1 ? true : false;
            if ( !form['needValueRemark'] ) {
                form['valueName'] = '';
                form['valueUnit'] = '';
            }
        }
    });
    
    const fetchCycleList = (obj)=>{
        let params = obj || { page:1, pageSize:10 };
        getCycleList(params)
        .then(res=>{
            if ( res.data.code === 200 ){
                cycleList.value = res.data.data;
                total.value = res.data.total;
            }
        })
    }
    onMounted(()=>{
        fetchCycleList();
    })
</script>
